package com.lagou.edu.handler;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.request.RpcRequest;
import com.lagou.edu.response.RpcResponse;
import com.lagou.edu.utils.SpringContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;

/**
 * @author 赵虎
 * @date 2020/11/25 11:58
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;

        String className = request.getClassName();
        String methodName = request.getMethodName();
        Object[] parameters = request.getParameters();
        Class<?>[] parameterTypes = request.getParameterTypes();

        Object bean = SpringContextUtil.getApplicationContext().getBean(className);

        Method method = bean.getClass().getMethod(methodName, parameterTypes);

        Object[] args = new Object[parameterTypes.length];

        for (int i = 0; i < args.length; i++) {
            Class<?> clazz = parameterTypes[i];
            args[i] = JSON.parseObject(JSON.toJSONString(parameters[i]),clazz);
        }

        Object invoke = method.invoke(bean, args);

        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setData(invoke);

        ctx.writeAndFlush(rpcResponse);
    }
}
